<?php


namespace Maowenke\tool;


class Mtool
{
    /**
     * 求经纬度距离
     * @param array|float[] $location1 数组，必须元素（long经度，lat纬度）
     * @param array|float[] $location2 数组，必须元素（long经度，lat纬度）
     * @param string $unit 距离单位 m=米, km=千米,mi=英里,ft=英尺
     * @return float|int
     */
    public static function getDistance(array $location1=['long'=>0,'lat'=>0],array $location2=['long'=>0,'lat'=>0],string $unit='m'){
        $EARTH_RADIUS = 6378.137;
        $radLat1 = self::rad($location1['lat']);
        $radLat2 = self::rad($location2['lat']);
        $a = $radLat1 - $radLat2;
        $b = self::rad($location1['long']) - self::rad($location2['long']);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s * 10000) / 10000;
        $s = $s*1000;
        if($unit=="km"){
            $s = $s/1000;
        }elseif ($unit=='mi'){
            $s = $s*0.000621371;
        }elseif ($unit=='ft'){
            $s = $s*3.281;
        }
        return $s;
    }
    protected static function rad($d){
        return $d * M_PI / 180.0;
    }
}